# -*- coding: utf-8 -*-
__author__ = 'ggcall'
import os
import sqlite3
from flask import Flask, g, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DB_NAME = 'npedi.db3'
DB_PATH = os.path.join(BASE_PATH, DB_NAME)
DEBUG=True
SECRET_KEY = 'jmN0XHZyj]X R8/X~,?!93LWRT/ArH'
SQLALCHEMY_DATABASE_URI='sqlite:///npedi.db3'

print DB_PATH
app = Flask(__name__)
app.config.from_object(__name__)
sa = SQLAlchemy(app)


def query_db(query, args=(), one=False):
    # print query
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value) for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv


def close_db():
    if hasattr(g, 'db'):
        g.db.close()


def connect_db():
    return sqlite3.connect(DB_PATH)


def request_wants_json():
    best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
    return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/html']


def del_none_val(d):
    for k in d.keys():
        if d[k] is None:
            d.pop(k)
    return d


def db_insert(tb, kv):
    def exe_sql(d):
        d = del_none_val(d)
        cols = ','.join(d.keys())
        vals = ','.join(['\'%s\'' % v.replace("'", "''") for v in d.values()])
        sql = 'insert into %s (%s) values(%s)' % (tb, cols, vals)
        # print sql
        query_db(sql)
    if type(kv) == list:
        for x in kv:
            if type(x) == dict:
                exe_sql(x)
    elif type(kv) == dict:
        exe_sql(kv)


def db_update(tb, kv):
    def exe_sql(d):
        d = del_none_val(d)
        cv = []

        cols = ['%s=' % k for k in d.keys()]
        vals = ['\'%s\'' % v for v in d.values()]
        for y in xrange(len(d)):
            cv.append('%s%s' % (cols[y], vals[y]))

        setval = ','.join(cv)
        #        print setval
        query_db('update %s set %s where seq_no=\'%s\'' % (tb, setval, d['SEQ_NO']))
    if type(kv) == list:
        for x in kv:
            if type(x) == dict:
                exe_sql(x)
    elif type(kv) == dict:
        exe_sql(kv)


@app.before_request
def before_request():
    g.db = connect_db()
    g.db.execute("PRAGMA foreign_keys=ON")


@app.teardown_request
def teardown_request(exception):
    close_db()


from views import *
if __name__ == "__main__":
    app.run(host='0.0.0.0',port=50003,debug=True)